//Track related
var trackID;
var trackerMode;

//Track related end
//GPS related
var gpsAccuracy = 9999;
var gpsHeading;
var gpsSpeed;
var gpsAltitude;
var gpsAltitudeAccuracy;
var gpsLongitude;
var gpsLatitude;
function getDeviceLocation() {
    if (navigator.geolocation !== undefined) {
        navigator.geolocation.watchPosition(getLocation);
    } else {
        updateFooter("Something's wrong");
        alert("Geolocation is not supported by your browser...");
    }
}
function getLocation(position) {    
    gpsLongitude = position.coords.longitude;
    gpsLatitude = position.coords.latitude;
    gpsAccuracy = position.coords.accuracy;
    gpsSpeed = position.coords.speed;
    gpsAltitude = position.coords.altitude;
    gpsAltitudeAccuracy = position.coords.altitudeAccuracy;
    gpsHeading = position.coords.heading;    
}
//GPS Related end


//Renderers
var news;
var mainview;
var footer;

function renderFooter(msg){
  var html = "Are you ready to track!";
  if (msg !== undefined){
     html=msg;
  }
  return html;
}
function roundDistance(value){
  return Math.round(value*10)/10;
}

function renderNews(){
  return "Welcome to Tracker!<br>Rules: <a href='http://crombs.com/tracker' target='support'>Crombs.com</a>";
}

function renderDistance(dist){
  if (dist === undefined){
     return "NA";
  } else {
    if (dist > 1000){
       return Math.round(dist/100)/10+"km";
    } else {
       return Math.round(dist,1) + "m";
    }
  }
}
function renderDatetime(stringDT){
  return new Date(stringDT.replace(" ", "T")+".000Z").toLocaleString();
}
function renderHelpMainView(){
  var html = "<div class='title'>Welcome!</div><div>Tracker is a game where one is the prey and others are Trackers</div>";
  html+="<div>Initializing the GPS, wait a few seconds...</div>";  
  return html;
}

function renderPreyStartView(id){
  var html="";
  html+="<div class='title'>You are the prey!</div><br>";
  html+="<div class='text'>Share this URL (Touch and hold to copy) with your friends:<br><center><a href='http://mobile.crombs.com/trackers?trackid="+id+"' target='_track'>Track ID</a></center></div>";
  html+="<br><br><div onclick='startPreyTrack();' class='button'>Go!</div>";
  return html;
}

function renderPreyStatus(){
  var html="";
  var preyName = getCookie("preyname");
  if (preyName === null || preyName.length===0){
     preyName="The Prey!";
  }
  html+="<div>Name: <input type=text maxlength=50 size=40 id='preyName' value='"+preyName+"'></div>";
  html+="<div>Status: <input type=text maxlength=100 size=40 id='preyStatus' value='Good luck!  Fools!'></div>";
  html+="<br><br><div onclick='stopPreyTrack();' class='button'>Stop!</div>";
  html+="<div>Any changes on your prey name or status will be updated automatically.<div>";
  return html;
}
function renderTrackerStatus(name,status,distance){
  var html="";
  
  html+="<div class='title'>Tracking: "+name+"</div><br>";
  html+="<div>Status: "+status+"</div><br><br><br>";
  html+="<div align=center class='distance'>"+renderDistance(distance)+"</div>";
  return html;
}
function renderTrackerLost(){
  var html="";
  html+="<div class='title'>This prey cannot be located...</div><br>";
  html+="<div>Make sure that the hunt as started or that is has not ended</div>";
  return html;
}

function updateGPSNotEnabled(){
  clearInterval(autoscan);
  var html = "<p class='title'>Your location could not be established...</p>";
  html+= "<p>Is your GPS enabled?</p>";
  html+= "<p>Make sure that your browser can access your geo-location in your device settings...</p>";
  updateMainview(html);
  updateFooter("Something's wrong...");

}
//Renderers end;

function initializeUI(){
   document.ontouchmove = function(e) {e.preventDefault()};
   setTimeout(getDeviceLocation,0);  
   news = document.getElementById("news");
   news.innerHTML = renderNews();
   mainview = document.getElementById("mainview");
   mainview.innerHTML = renderHelpMainView();
   mainview.ontouchmove = function(e) {e.stopPropagation()};
   footer = document.getElementById("footer");  
   trackID=gup("trackid");
   if (trackID !== undefined && trackID.length>0){
      trackerMode="Tracker";
      setTimeout(startTracker,5000);
   } else {
      setTimeout(createTrack,5000);
      trackerMode="Prey";
   }
   footer.innerHTML = renderFooter(trackerMode);

  if(navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false ){
    //distance.addEventListener("touchstart",function(){distance.className="distanceTouched";scan();return false;},false);
    //distance.addEventListener("touchend",function(){setAutoScan();},false);  
  } else{   
   //distance.addEventListener("mousedown",function(){distance.className="distanceTouched";scan();return false;},false);
   //distance.addEventListener("mouseup",function(){setAutoScan();},false);
  }    
}

function updateMainview(html){
  mainview.style["opacity"] = 0;  
  setTimeout(function(){mainview.innerHTML=html;mainview.style["opacity"] = 1;},700);    
}
function updateFooter(msg){
  footer.style["opacity"] = 0;
  setTimeout(function(){footer.innerHTML=renderFooter(msg); footer.style["opacity"] = 1;},700);   
}

var autoscan;


//Crombs Related

function startTracker(){
   clearInterval(autoscan);
   setTimeout(updateTrackerTrack,0);
   autoscan = setInterval(updateTrackerTrack,15000);
}
function startPreyTrack(){
   clearInterval(autoscan);
   updateMainview(renderPreyStatus());
   setTimeout(function(){updatePreyTrack("create");},1000);
   autoscan = setInterval(updatePreyTrack,15000);
}

function stopPreyTrack(){
   clearInterval(autoscan);
   updatePreyTrack("delete");
   setTimeout(createTrack,1000);  
}

function updatePreyTrack(action){
  var xmlhttp;
  var txt,i;
  if(gpsLongitude===undefined){
     updateGPSNotEnabled();
     return;
  }
  var name = document.getElementById("preyName").value;
  var status = document.getElementById("preyStatus").value;
  setCookie("preyName",name,365);
  var url = "updatetracks.php?id="+trackID+"&lon="+gpsLongitude+"&lat="+gpsLatitude+"&name="+encodeURIComponent(name)+"&status="+encodeURIComponent(status)+"&action="+action;
  //console.log(url);
  if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  
  xmlhttp.open("POST",url,true);
  xmlhttp.setRequestHeader("Content-Type","text/xml");
  xmlhttp.overrideMimeType('text/xml');
  xmlhttp.send();
  updateFooter("You are the prey!");
  
}
function updateTrackerTrack(){
  var xmlhttp;
  var txt,i;
  if(gpsLongitude===undefined){
     updateGPSNotEnabled();
     return;
  }
  updateFooter("Scanning...");
  var url = "track.php?id="+trackID+"&lon="+gpsLongitude+"&lat="+gpsLatitude;
  //console.log(url);
  if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState===4 && xmlhttp.status===200){
      var parser = new DOMParser();
      var x = parser.parseFromString(xmlhttp.response, "text/xml").getElementsByTagName("crombtrack");
      var mainViewHTML = "";

      if (x.length === 0 ){
         //Nothing inside 100km...
         updateMainview(renderTrackerLost());
         updateFooter("Something's wrong...");                  
      } else {        
        for (i=0;i<x.length;i++){
          var name=x[i].getAttribute("name");
          var status=x[i].getAttribute("status");
          var dist=x[i].getAttribute("dist"); //in meters
          updateFooter("Prey position updated");
          updateMainview(renderTrackerStatus(name,status,dist));
          break; 
        }
      }
    }
  }
  xmlhttp.open("POST",url,true);
  xmlhttp.setRequestHeader("Content-Type","text/xml");
  xmlhttp.overrideMimeType('text/xml');
  xmlhttp.send();
}
function createTrack()
{
  var xmlhttp;
  var txt,i;
  if(gpsLongitude===undefined){
     updateGPSNotEnabled();
     return;
  }
  var url = "createtrack.php";
  if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState===4 && xmlhttp.status===200){
      var parser = new DOMParser();
      var x = parser.parseFromString(xmlhttp.response, "text/xml").getElementsByTagName("track");
      var mainViewHTML = "";

      if (x.length === 0 ){
         //Nothing inside 100km...
         updateMainview("Could not create track ID");
         updateFooter("Something's wrong...");                  
      } else {        
        for (i=0;i<x.length;i++){
          trackID=x[i].getAttribute("id");
          updateFooter("Touch GO to start the hunt!");
          updateMainview(renderPreyStartView(trackID));
          break; 
        }
        
      }
    }
  };
  xmlhttp.open("POST",url,true);
  xmlhttp.setRequestHeader("Content-Type","text/xml");
  xmlhttp.overrideMimeType('text/xml');
  xmlhttp.send();
}
//Crombs Related End

//Maps related
function showGoogleMap() {
  if(gpsLongitude===undefined){
     updateGPSNotEnabled();
     return;
   }
  clearInterval(autoscan);
  distance.className="distance";
  
  updateFooter("You are here!");
  mainview.innerHTML = "<div id='map' class='mainview'></div>";
  var mapOptions = {
    zoom: 16,
    center: new google.maps.LatLng(gpsLatitude,gpsLongitude),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map"),
                                mapOptions);

  var image = 'images/mapflag.png';
  var myLatLng = new google.maps.LatLng(gpsLatitude,gpsLongitude);
  var beachMarker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      icon: image
  });
}
//Maps related end

function setCookie(c_name, value, exdays)
    {
      var exdate = new Date();
      exdate.setDate(exdate.getDate() + exdays);
      var c_value = escape(value) + ((exdays === null) ? "" : "; expires=" + exdate.toUTCString());
      document.cookie = c_name + "=" + c_value;
    }
function getCookie(c_name)
    {
      var c_value = document.cookie;
      var c_start = c_value.indexOf(" " + c_name + "=");
      if (c_start === -1)
      {
        c_start = c_value.indexOf(c_name + "=");
      }
      if (c_start === -1)
      {
        c_value = null;
      }
      else
      {
        c_start = c_value.indexOf("=", c_start) + 1;
        var c_end = c_value.indexOf(";", c_start);
        if (c_end === -1)
        {
          c_end = c_value.length;
        }
        c_value = unescape(c_value.substring(c_start, c_end));
      }
      return c_value;
}
function gup( name ){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  
  var regexS = "[\\?&]"+name+"=([^&#]*)";  
  var regex = new RegExp( regexS );  
  var results = regex.exec( window.location.href ); 
   if( results == null )    return "";  
  else    return results[1];
}